package csd.wyaiyr.com.config;

import com.alibaba.fastjson.JSONObject;
import csd.wyaiyr.com.utils.RedisUtil;
import csd.wyaiyr.com.utils.StringUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.io.IOException;
import java.io.PrintWriter;


@Slf4j
//@Component
public class CheckTokenFilter implements Filter {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String servletPath = req.getServletPath();
        log.info("servletPath={}",servletPath);
        if(servletPath.contains("/test")
            || servletPath.contains("/login")
            || servletPath.contains("/doc") || servletPath.contains("/webjars") || servletPath.contains("/v3/api-docs")
            || servletPath.contains("/common")
//                || servletPath.contains("/childrencall")
            || servletPath.contains("/getToken")){
            //放行
            chain.doFilter(request,response);
        }else{
            String accesstoken = req.getHeader("accesstoken");
            String userId = req.getHeader("mobilePhoneNumber");
            log.info("userId={},accesstoken={}",userId,accesstoken);
            if(null == userId || null == accesstoken ){
                resp.setContentType("text/html; charset=UTF-8");
                resp.setStatus(500);
                PrintWriter out = response.getWriter();
                out.print(JSONObject.toJSONString(BaseResult.error(401,"请登录！")));
                out.flush();
                out.close();
                return ;
            }else{
                String redistoken = redisUtil.get(userId);

                if(StringUtil.isEmpty(redistoken) || !redistoken.equals(accesstoken)){
                    resp.setContentType("text/html; charset=UTF-8");
                    resp.setStatus(401);
                    PrintWriter out = response.getWriter();
                    out.print(JSONObject.toJSONString(BaseResult.error(401,"登录已失效，请退出重新登录！")));
                    out.flush();
                    out.close();
                }else{
                    //放行
                    chain.doFilter(request,response);
                }
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("[ {} ] 创建啦过滤器...", this.getClass().getSimpleName());
    }

    @Override
    public void destroy() {
        log.info("[ {} ] 被摧毁啦...", this.getClass().getSimpleName());
    }
}
